import { Input, View } from "@tarojs/components";
import { useDebounce } from "ahooks";
import { useEffect, useState } from "react";
import ByRow from "../ui/ByRow";

type InputNumberProps = {
  prefix?: string;
  defaultValue?: number | string;
  precision?: number;
  className?: string;
  placeholder?: string;
};

type InputNumberEvent = {
  onChange: (e: number) => void;
};

export default ({
  prefix,
  placeholder,
  defaultValue,
  precision = 0,
  className,
  onChange,
}: InputNumberProps & InputNumberEvent) => {
  const [value, setValue] = useState<string | number>(defaultValue || "");
  const debouncedValue = useDebounce(value, { wait: 500 });

  useEffect(() => {
    let val = debouncedValue;

    if (val) {
      val = Number(
        Number(
          val
            .toString()
            .replace(/[^\d.]/g, "")
            .replace(/^([^.]*\.)|\./g, (m, p1) => p1 || "")
        ).toFixed(precision)
      );
    }

    setValue(val);
    onChange(Number(val));
  }, [debouncedValue]);

  const handleInput = (e) => {
    const val = e.detail.value;
    setValue(val);
  };

  return (
    <ByRow
      align="center"
      className="w-full border-1 border-line-light rounded-md"
    >
      {prefix && <View className="text-third pl-2">{prefix}</View>}
      <Input
        type="digit"
        className={className}
        placeholder={placeholder}
        value={value + ""}
        onInput={handleInput}
      />
    </ByRow>
  );
};
